import "@utils/common.js";
import lax from "lax.js";
import "./index.scss";
let ejs = require("ejs/ejs.min.js");

var TData = [{
        "companyId": 1,
        "companyName": "艾森汇智",
        "categories": [{
            "categoryId": "公司动态",
            "categoryName": "公司动态"
        }, {
            "categoryId": "行业资讯",
            "categoryName": "行业资讯"
        }]
    },
    {
        "companyId": 2,
        "companyName": "晓智信息",
        "categories": [{
            "categoryId": "公司动态",
            "categoryName": "公司动态"
        }]
    }
]
var company = $('#company').val();
var category = $('#category').val();
var coverImage = ''
var title = $('#title').val();
var summary = $('#summary').val();

function GetQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return null;
}

// 请求公司及其类别的数据
function loadCompanies(getID, found) {
    $.ajax({
        url: '/api/news/getCompanyEnumList',
        type: 'GET',
        dataType: 'json',
        success: function (data) {
            // 清空公司select的现有选项
            $('#company').empty().append('<option value="">请选择</option>');
            // 遍历返回的公司数据，并添加到公司select中
            $.each(data, function (index, company) {
                $('#company').append($('<option></option>').val(company.code).text(company.desc));
            });
            // 弹窗标题
            if (getID) {
                $('#myModalLabel').text('编辑发布')
                company = found.company ? found.company : '';
                category = found.category ? found.category : '';
                coverImage = found.image ? found.image : '';
                title = found.title ? found.title : '';
                summary = found.subcont ? found.subcont : '';
                // 类别列表生成&编辑回显
                var companyData = TData.filter(companys => companys.companyId == company)[0] // 调整索引以匹配数组索引
                // 清空类别select的现有选项
                $('#category').empty().append('<option value="">请选择类别</option>');
                // // 如果公司被选中且存在类别数据，则添加类别选项
                if (category && companyData) {
                    const data = companyData.categories

                    $.each(data, function (index, category) {
                        $('#category').append($('<option></option>').val(category.categoryId).text(category.categoryName));
                    });

                }
                // 将值设置到对应的输入框中
                $('#company').val(company);
                $('#category').val(category);
                $('#title').val(title);
                $('#summary').val(summary);
                const location = `${process.env.BASE_URL}` + `api/static` + coverImage
                $('#coverPreview').attr('src', location);
                $('#coverPreview').show(); // 显示图片预览
            } else {
                $('#myModalLabel').text('新增发布')
            }
            // 启用发布按钮
            $('#saveButton').prop('disabled', false);
        },
        error: function () {
            alert('加载公司数据失败');
        }
    });
}

//新闻新增保存
function PutNews(fields) {
    // 获取TinyMCE编辑器的内容
    var content = tinyMCE.activeEditor.getContent();
    $.ajax({
        type: "put",
        url: `${process.env.BASE_URL}` + `api/news`,
        dataType: "json",
        contentType: "application/json",
        data: JSON.stringify({
            "cont": content,
            "company": fields.company,
            "category": fields.category,
            "type": "Company",
            "image": fields.coverImage,
            "title": fields.title,
            "time": getCurrentDateTime(),
            "subcont": fields.summary
        }),
        success(response) {
            if (response) {
                tinyMCE.activeEditor.setContent('<h3 class="some-class">保存成功...</h3>');
                setTimeout(() => {
                    tinyMCE.activeEditor.setContent('');
                    $('<a href="./News_Company.html"></a>').appendTo('body')[0].click();
                }, 1000);
            }
        }
    })
}

//新闻编辑保存
function EditNews(fields, id) {
    var content = tinyMCE.activeEditor.getContent();

    $.ajax({
        type: "put",
        url: `${process.env.BASE_URL}` + `api/news`,
        dataType: "json",
        contentType: "application/json",
        data: JSON.stringify({
            "category": fields.category,
            "cont": content,
            "company": fields.company,
            "type": "Company",
            "image": fields.coverImage,
            "title": fields.title,
            "subcont": fields.summary,
            // "time": getCurrentDateTime(),
            "id": id
        }),
        success(response) {
            if (response) {
                tinyMCE.activeEditor.setContent('<h3 class="some-class">编辑成功...</h3>');
                setTimeout(() => {
                    tinyMCE.activeEditor.setContent('');
                    $('<a href="./News_Company.html"></a>').appendTo('body')[0].click();
                }, 1000);
            }
        }
    })
}

function getCurrentDateTime() {
    const now = new Date(); // 获取当前日期和时间

    // 获取年、月、日、时、分、秒
    const year = now.getFullYear();
    const month = now.getMonth() + 1; // 月份是从0开始的，所以需要加1
    const day = now.getDate();
    const hours = now.getHours();
    const minutes = now.getMinutes();
    const seconds = now.getSeconds();

    // 格式化月份和日期，确保它们是两位数
    const formattedMonth = month < 10 ? '0' + month : month;
    const formattedDay = day < 10 ? '0' + day : day;
    const formattedHours = hours < 10 ? '0' + hours : hours;
    const formattedMinutes = minutes < 10 ? '0' + minutes : minutes;
    const formattedSeconds = seconds < 10 ? '0' + seconds : seconds;

    // 构建并返回格式化的日期时间字符串
    return `${year}-${formattedMonth}-${formattedDay} ${formattedHours}:${formattedMinutes}:${formattedSeconds}`;
}

function validateVideo(file) {
    const isMP4 = file.type === "video/mp4";
    const isLt3M = file.size / 1024 / 1024 < 5;

    if (!isMP4) {
        alert("上传视频必须为 MP4 格式！");

        return false;
    }

    if (!isLt3M) {
        alert("上传视频大小限制 5M 以内！");

        return false;
    }

    const duration = getVideoDuration(file);
    if (duration > 60) {
        alert("上传视频时长不能超过 60 秒！");

        return false;
    }

    return true;
}

function getVideoDuration(file) {
    return new Promise((resolve) => {
        const videoElement = document.createElement("video");
        videoElement.src = URL.createObjectURL(file);
        videoElement.addEventListener("loadedmetadata", () => {
            resolve(videoElement.duration);
        });
    });
}



$(function () {

    console.log(getCurrentDateTime());

    var getID = GetQueryString('id')
    var id = ''

    // 禁用按钮
    $('#saveButton').prop('disabled', true);

    // 初始化弹窗
    $('#myModal').modal({
        show: false
    });

    // 图片上传
    const example_image_upload_handler = (blobInfo, progress) =>
        new Promise((resolve, reject) => {
            const xhr = new XMLHttpRequest();
            const url = `${process.env.BASE_URL}` + `api/upload/multipartFile`
            xhr.withCredentials = false;
            xhr.open("POST", url);

            xhr.upload.onprogress = (e) => {
                progress((e.loaded / e.total) * 100);
            };
            xhr.onload = () => {
                if (xhr.status === 403) {
                    reject({
                        message: "HTTP错误：" + xhr.status,
                        remove: true
                    });
                    return;
                }

                if (xhr.status < 200 || xhr.status >= 300) {
                    reject("HTTP错误：" + xhr.status);
                    return;
                }

                const json = JSON.parse(xhr.responseText);

                if (!json || typeof json.location != "string") {
                    reject("无效的JSON格式： " + xhr.responseText);
                    return;
                }
                const location = `${process.env.BASE_URL}` + `api/static` + json.location
                // http: //192.168.10.231:8080/static
                // resolve(json.location);
                resolve(location);
            };
            xhr.onerror = () => {
                reject("由于XHR传输错误，图像上传失败。错误代码 " + xhr.status);
            };

            const formData = new FormData();
            formData.append("file", blobInfo.blob(), blobInfo.filename());

            xhr.send(formData);
        });

    const example_file_picker_callback = (callback, value, meta) => {
        if (meta.filetype === "media") {
            const input = document.createElement("input");
            input.setAttribute("type", "file");
            const that = this;
            input.onchange = async function () {
                const file = this.files[0];
                const isValid = await validateVideo(file);
                if (isValid) {
                    var formData = new FormData();
                    formData.append('file', file); // 假设file变量是你的视频文件

                    $.ajax({
                        url: `${process.env.BASE_URL}` + `api/upload/multipartFile`,
                        type: 'POST',
                        data: formData,
                        processData: false,
                        contentType: false,
                        success: function (response) {
                            callback(`${process.env.BASE_URL}` + `api/static` + response.location);
                        },
                        error: function (xhr, status, error) {
                            callback(error);
                        }
                    });
                } else {
                    callback();
                }
            };

            input.click();
        }
    }

    tinyMCE.init({
        selector: "#mytextarea", // 选择器，要初始化的textarea的ID
        // 其他配置项
        auto_focus: true,
        branding: false,
        language_url: window.PPATH + "/libs/tinymce/langs/zh_CN.js",
        language: "zh_CN",
        toolbar: true, //工具栏
        menubar: true, //菜单栏
        branding: false, //右下角技术支持
        inline: false, //开启内联模式
        elementpath: false,
        min_height: 400, //最小高度
        max_height: 500, //高度
        skin: "oxide",
        toolbar_sticky: true,
        visualchars_default_state: true, //显示不可见字符
        image_caption: true,
        paste_data_images: true,
        relative_urls: false,
        // remove_script_host : false,
        removed_menuitems: "newdocument", //清除“文件”菜单
        plugins: "formatpainter,lists, advlist,autolink,autoresize,charmap,code,codesample,emoticons,fullscreen,image,media,pagebreak,preview,searchreplace,table,visualchars,wordcount", //依赖lists插件
        toolbar1: "undo redo | blocks | bold italic indent outdent  alignleft aligncenter alignright | bullist numlist ",
        toolbar2: "formatpainter emoticons alignjustif fullscreen  image insertdatetime media  preview  searchreplace textcolor wordcount",

        //选中时出现的快捷工具，与插件有依赖关系
        // images_upload_url: `${process.env.BASE_URL}` + `upload/multipartFile`,
        menu: {
            format: {
                title: 'Format',
                // blocks fontfamily
                items: 'bold italic underline strikethrough superscript subscript codeformat | styles fontsize align lineheight | forecolor backcolor | language | removeformat'
            },

        },
        setup: function (editor) {

            editor.on("change", function () {
                editor.save();
            });
            // 监听初始化完成的事件
            editor.on('init', function () {
                $.ajax({
                    type: "post",
                    // url:  'http://192.168.10.231:8080/file/page',
                    url: `${process.env.BASE_URL}` + `api/news/page`,
                    dataType: "json",
                    contentType: "application/json",
                    data: JSON.stringify({
                        "current": 1,
                        "size": 10
                    }),
                    success(response) {
                        if (response.records.length > 0) {

                            var found = response.records.find(function (item) {
                                return item.id == getID;
                            });
                            var data = found ? found.cont : false
                            id = found ? found.id : ''
                            if (data) {
                                editor.setContent(data);
                            } else {
                                editor.setContent('');
                            }
                            //弹窗select数据
                            loadCompanies(getID, found)

                        }
                    },
                    error(xhr, textStatus, errorThrown) {
                        // 请求失败的回调函数，xhr是XMLHttpRequest对象，textStatus是状态错误信息，errorThrown是跟踪异常对象
                        editor.setContent('编辑出错' + xhr + textStatus + errorThrown);

                    },
                })
                // 在初始化完成后回填数据
                // var data = '<h3>数据回填</h3><video style="display: table; margin-left: auto; margin-right: auto;" controls="controls" width="300" height="150"><source src="http://www.i-sen.cn/public/Video/Profile.mp4" type="video/mp4"></video><br><img style="display: block; margin-left: auto; margin-right: auto;" src="http://192.168.10.231:8080/static/uploadFile/image/a14bf82bf7a3435398bb1cc410c7bac4.png" alt="2" width="469" height="264"></>';
                // setTimeout(() => {
                //     editor.setContent(data);
                // }, 2000);
            });
            // 在图片被删除时触发的逻辑处理

            // editor.on('KeyDown', function (e) {

            //     if ((e.keyCode == 8 || e.keyCode == 46) && editor.selection) { // delete & backspace keys

            //         var selectedNode = editor.selection.getNode(); // get the selected node (element) in the editor

            //         if (selectedNode && selectedNode.nodeName == 'IMG') {

            //            console.log('图片删除');
            //         }
            //     }
            // });
        },
        images_upload_handler: example_image_upload_handler,
        // 视频上传----
        file_picker_callback: example_file_picker_callback,
    });
    $(document).ready(function () {

        $("#saveButton").click(function () {
            // 显示弹窗
            $('#myModal').modal('show');
        });
        // 编辑提交
        $("#saveButton2").click(function () {
            // 获取TinyMCE编辑器的内容

        });
        // 弹窗部分-----------------

        // 当公司选择变化时，加载相应的类别
        $('#company').change(function () {
            var companyId = $(this).val();
            var companyData = TData.filter(company => company.companyId == companyId)[0] // 调整索引以匹配数组索引
            // 清空类别select的现有选项
            $('#category').empty().append('<option value="">请选择类别</option>');
            // // 如果公司被选中且存在类别数据，则添加类别选项
            if (companyId && companyData) {
                const data = companyData.categories
                $.each(data, function (index, category) {
                    $('#category').append($('<option></option>').val(category.categoryId).text(category.categoryName));
                });

            }
        });

        // 文件输入框变化事件---弹窗上传
        $('#coverImage').change(function () {
            var input = this;
            var url = $(this).val();
            var ext = url.substring(url.lastIndexOf('.') + 1).toLowerCase();
            if (input.files && input.files[0] && (ext === "gif" || ext === "png" || ext === "jpeg" || ext === "jpg")) {
                var formData = new FormData();
                formData.append('file', input.files[0]);
                // 使用AJAX发送FormDat
                $.ajax({
                    url: `${process.env.BASE_URL}` + `api/upload/multipartFile`, // 你的图片上传API端点
                    type: 'POST',
                    data: formData,
                    processData: false, // 不处理数据 
                    contentType: false, // 不设置内容类型
                    success: function (response) { // 处理上传成功的响应 
                        coverImage = response.location
                        $('#coverImage').hide(); // 隐藏路径
                        const location = `${process.env.BASE_URL}` + `api/static` + response.location
                        $('#coverPreview').attr('src', location);
                        $('#coverPreview').show(); // 显示图片预览
                    },
                    error: function (xhr, status, error) {
                        // 处理上传错误 
                        console.error(error);
                    }
                });

            } else {
                $('#coverPreview').attr('src', '#');
                $('#coverPreview').hide(); // 隐藏图片预览
            }
        });

        // 保存按钮点击事件
        $('#FormSaveButton').click(function () {
            var fields = {
                company: $('#company').val(),
                category: $('#category').val(),
                coverImage: coverImage || '',
                title: $('#title').val(),
                summary: $('#summary').val()
            };
            // 表单验证等逻辑

            if (fields.company && fields.category && fields.coverImage && fields.title && fields.summary) {
                // console.log('数据保存' + getID);
                if (getID) {
                    EditNews(fields, getID)
                } else {
                    // 新增保存
                    PutNews(fields)
                }
                $('#myModal').modal('hide');

            } else {
                var fieldLabels = {
                    company: '公司信息',
                    category: '分类信息',
                    coverImage: '封面图片',
                    title: '标题',
                    summary: '摘要'
                };
                for (var key in fieldLabels) {
                    var id = "#" + key
                    if (!fields[key]) { // 检查字段值是否为空
                        console.log(id);
                        $(id).addClass('is-invalid');
                        if (key == 'coverImage') {
                            alert(fieldLabels[key] + '不能为空');
                        }
                    } else {
                        $(id).removeClass('is-invalid');
                    }
                }

            }

        });


    });
});